package com.qf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;

/**
 * @author zhaojian
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    /**
     * 跳转到上传页面
     * @return
     */
    @RequestMapping("/toUpload")
    public String toUpload() {
        return "fileupload";
    }

    /**
     * 上传
     * @param source
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/test1")
    @ResponseBody
    public String uploadFile(MultipartFile source , HttpServletRequest request) throws Exception {
        //1. 获取文件名
        String fileName = source.getOriginalFilename();
        //2. 获取文件内容
        InputStream inputStream = source.getInputStream();
        //3. 获取文件大小
        long size = source.getSize();

        //4. 拼接返回的访问这个文件的路径
        String contextPath = request.getContextPath();

        String url = contextPath + "/upload/" + fileName;
        //5. 将文件保存到磁盘中
        source.transferTo(new File("D:\\ideaWorkspace\\workspace11\\springmvcDemo01\\target\\springmvcDemo01-1" +
                ".0-SNAPSHOT\\upload\\"+fileName));
        //todo 6. 将文件保存的路径存入数据库的表中

        //7. 将文件保存的路径返回
        return url;
    }
}
